import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from models import *

class MainPage(webapp.RequestHandler):
	def get(self):
		if users.get_current_user():
			currentUser = users.get_current_user()
			householdQuery = Household.all()
			householdQuery.filter("user =",currentUser)
			home = householdQuery.get()
			if not home:
				home = Household(user=currentUser)
				home.put()
				me = Roommate(household=home,name="me")
				me.put()
				roommates = [me]
			else:
				roommates = Roommate.all().filter("household =",home).fetch(20)
				
			logoutUrl = users.create_logout_url(self.request.uri)
			templateValues = {
				"username" : currentUser.nickname(),
				"logoutUrl":logoutUrl,
				"home":home,
				"roommates":roommates
			}
			path = os.path.join(os.path.dirname(__file__),"app.html")
		else:
			loginUrl = users.create_login_url(self.request.uri)
			templateValues = {"loginUrl" : loginUrl}
			path = os.path.join(os.path.dirname(__file__),"landing.html")
		self.response.out.write(template.render(path,templateValues))
application = webapp.WSGIApplication([('/',MainPage)],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
